package com.ecube.maintenance.components.fragment;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.ecube.maintenance.R;
import com.ecube.maintenance.biz.apis.impl.OrderAction;
import com.ecube.maintenance.biz.commons.ICCallBack;
import com.ecube.maintenance.biz.commons.ICTException;
import com.ecube.maintenance.components.widget.LoadingDialog;
import com.ecube.maintenance.components.widget.UserInfoView;
import com.ecube.maintenance.pojos.OrderInfo;
import com.ecube.maintenance.pojos.ProductInfo;
import com.ecube.maintenance.pojos.SellerInfo;
import com.ecube.maintenance.pojos.UserInfo;
import com.ecube.maintenance.utils.Bog;
import com.ecube.maintenance.utils.StringUtil;
import com.sleepbot.datetimepicker.time.RadialPickerLayout;
import com.sleepbot.datetimepicker.time.TimePickerDialog;

import java.util.Calendar;

public class OrderConfirmationFragment extends Fragment
        implements TimePickerDialog.OnTimeSetListener {


    public static final String TIME_PICKER_TAG = "timepicker";
    public static final String ARG_SELLER_INFO = "seller_info";
    public static final String ARG_PRODUCT_INFO = "product_info";
    public static final String ARG_ARRIVE_DATE = "arrive_date";
    final Calendar calendar = Calendar.getInstance();
    final TimePickerDialog timePickerDialog = TimePickerDialog
            .newInstance(this, calendar.get(Calendar.HOUR_OF_DAY),
                    calendar.get(Calendar.MINUTE), false, true);
    SellerInfo sellerInfo;
    ProductInfo productInfo;
    String arriveTime, arriveDate;
    TextView serviceTime, serviceName, serviceOriginPrice, sellerName;
    private TextView mTimePickerButton;
    private TextView mSubmitButton;
    private UserInfoView uiv;
    private EditText mDrivedMile;
    CheckBox mCheckUserPolicy;
    TextView mCheckUserPolicyText;
    boolean goToSeeUserPolicy;

    public OrderConfirmationFragment() {
    }

    public static OrderConfirmationFragment newInstance(
            SellerInfo sellerInfo, ProductInfo productInfo, String arriveDate) {
        OrderConfirmationFragment fragment = new OrderConfirmationFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_SELLER_INFO, sellerInfo);
        args.putSerializable(ARG_PRODUCT_INFO, productInfo);
        args.putSerializable(ARG_ARRIVE_DATE, arriveDate);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            sellerInfo = (SellerInfo) getArguments().getSerializable(ARG_SELLER_INFO);
            productInfo = (ProductInfo) getArguments().getSerializable(ARG_PRODUCT_INFO);
            arriveDate = getArguments().getString(ARG_ARRIVE_DATE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        configureActionBar();
    }

    private void configureActionBar() {
        ActionBar actionBar = getActivity().getActionBar();
        assert actionBar != null;
        View v = actionBar.getCustomView();
        if (v != null) {
            v.setVisibility(View.GONE);
        }
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle("订单确认");
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        menu.clear();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_order_confirmation, container, false);
        serviceName = (TextView) rootView.findViewById(R.id.service_name);
        serviceTime = (TextView) rootView.findViewById(R.id.service_time);
        serviceOriginPrice = (TextView) rootView.findViewById(R.id.service_price);
        sellerName = (TextView) rootView.findViewById(R.id.seller_name);
        mDrivedMile = (EditText) rootView.findViewById(R.id.input_drive_mile);
        mCheckUserPolicy = (CheckBox) rootView.findViewById(R.id.user_policy_check);
        mCheckUserPolicyText = (TextView) rootView.findViewById(R.id.user_policy_text);
        mCheckUserPolicyText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToSeeUserPolicy = true;
                getFragmentManager().beginTransaction()
                        .hide(OrderConfirmationFragment.this)
                        .add(R.id.container,ViewUserPolicyFragment.newInstance())
                        .addToBackStack(null).commit();
            }
        });
        serviceOriginPrice.setText("￥" + productInfo.getDiscountPrice());
        serviceTime.setText(arriveDate + "  " + productInfo.getServiceStartTime()
                + "~" + productInfo.getServiceEndTime());
        serviceName.setText(productInfo.getProductName());
        sellerName.setText(sellerInfo.getSpName());

        mTimePickerButton = (TextView) rootView.findViewById(R.id.tv);
        mTimePickerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] t = mTimePickerButton.getText().toString().split(":");
                timePickerDialog.setStartTime(Integer.parseInt(t[0]), Integer.parseInt(t[1]));
                timePickerDialog.setServiceTime(productInfo.getServiceStartTime(),
                        productInfo.getServiceEndTime());
                timePickerDialog.show(getActivity().getFragmentManager(), TIME_PICKER_TAG);
            }
        });
        mTimePickerButton.setText(productInfo.getServiceStartTime());
        arriveTime = mTimePickerButton.getText().toString();

        uiv = (UserInfoView) rootView.findViewById(R.id.view_user_info);
        mSubmitButton = (TextView) rootView.findViewById(R.id.btn_order_submit);
        mSubmitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitOrder();

            }
        });
        return rootView;
    }

    private void submitOrder() {
        String mile = mDrivedMile.getText().toString();
        if ( TextUtils.isEmpty(mile) ){
            Bog.toast("请输入里程");
            return;
        }
        if ( !mCheckUserPolicy.isChecked() ){
            Bog.toast("请勾选同意用户服务协议");
            return;
        }
        if(!uiv.checkUserInput())return;
        UserInfo.getInstance().setDriveMile(mile);
        final LoadingDialog dialog = new LoadingDialog(getActivity());
        dialog.setTipText(getString(R.string.message_loading_submit_order));
        dialog.show();
        dialog.getDialog().setCancelable(false);
        String arrive = arriveDate + " " + arriveTime + ":00";
        productInfo.setServiceDate(arriveDate);
        OrderAction.submit(UserInfo.getInstance(), sellerInfo,
                productInfo, arrive, new ICCallBack<OrderInfo>() {
                    @Override
                    public void done(OrderInfo result, ICTException exception) {
                        if (exception == null) {
                            Bog.toast(R.string.message_submit_order_success);
                            Fragment f = OrderDetailFragment.newInstance(result);
                            getFragmentManager().beginTransaction()
                                    .setCustomAnimations(R.anim.fade_in, R.anim.fade_out)
                                    .hide(OrderConfirmationFragment.this)
                                    .add(R.id.container, f).addToBackStack(null).commit();
                        } else {
                            Bog.toast("提交失败:" + exception.getMessage());
                        }
                        dialog.getDialog().dismissDialogger();
                    }
                });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            if (goToSeeUserPolicy){
                super.onHiddenChanged(hidden);
            } else {
                getFragmentManager().popBackStack();
            }

        } else
            super.onHiddenChanged(hidden);
    }
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
        Bog.i("new time:" + hourOfDay + ":" + minute);
        arriveTime = hourOfDay + ":" + (minute < 10 ? "0" + minute : minute);
        mTimePickerButton.setText(arriveTime);
    }


}
